import { apiUserGetLoginUser, cmsmeCmsmeVoList, purtbSelectAll, purtbSelectPurtb } from '@/api/url/salesOrderManagement';
import router from '@/router';
import { EFTimeFormatConversion, formatDate, isNullPm, spaceTime } from '@/utils/baseMethods';
import { PURTBCHANGE } from '@/utils/EFCODE';
import { reactive, watch } from 'vue';

import notification from '@arco-design/web-vue/es/notification';
import XEClipboard from 'xe-clipboard';
import { VXETable } from 'vxe-table';
import { dayjs } from '@arco-design/web-vue/es/_utils/date';

export default function importConfig() {
  const base = reactive<any>({
    pagination: {
      total: 100,
      current: 1,
      pageSize: 10,
    },
    tabelList: null,
    checkFrom: {
      requisitionType: null,
      requisitionNo: null,
      time: null,
      productName: null,
      articleNumber: null,
      requirementDate: null,
      requisitionDepartment: '',
    },
    ggDomas: [],
    getOmnList: [],
    tableRef: null,
    visible: false,
    desData: null,
    featureData: {
      sectionTime: [],
      mergingMethod: '同供应商同单据合并',
      primaryMeter: false,
      sublist: false,
    },
    defaultSelecteRowKeys: [],
    tabelValue: false,
    section: null,
  });

  const init = () => {
    base.tabelValue = false;
    getTable();
    sectionOption();
    // apiUserGetLoginUser('').then((reb: any) => {
    //   if (reb.code == '200') {
    //     const steamOpmc = {
    //       userNo: reb.data.ma001,
    //       userName: reb.data.ma002,
    //     };
    //     localStorage.setItem('POOMPMO', JSON.stringify(steamOpmc));
    //   }
    // });
  };

  /**
   * @exports defaultValueWriteBack 数据回写绑定
   */
  const defaultValueWriteBack = () => {
    const steam: any = localStorage.getItem('BLISOK');
    base.defaultSelecteRowKeys = [];
    if (!isNullPm(steam)) {
      JSON.parse(steam).map((reb: any) => {
        reb?.getOmnList.map((res: any) => {
          base.defaultSelecteRowKeys.push(res.requisitionType + res.requisitionNo + res.requisitionNumber);
          base.getOmnList.push(res);
        });
      });
    }

    base.tabelValue = true;
  };

  const getTable = () => {
    const steam = `?size=${base.pagination.pageSize}&current=${base.pagination.current}`;

    const steamDom = {};
    const relt = base.checkFrom;
    if (relt.time) {
      relt.time = dayjs(relt.time).format('YYYYMMDD');
    }
    if (relt.requirementDate) {
      relt.requirementDate = dayjs(relt.requirementDate).format('YYYYMMDD');
    }

    Object.keys(base.checkFrom).map((res: any) => {
      if (!isNullPm(base.checkFrom[res])) {
        steamDom[res] = base.checkFrom[res];
      }
    });
    purtbSelectAll(steam, steamDom).then((res: any) => {
      if (res.code === '200') {
        const steam = res.data.records;
        steam.map((rea: any) => {
          Object.keys(rea).map((reb: any) => {
            if (!isNullPm(rea[reb]) && typeof rea[reb] == 'string') {
              rea[reb] = rea[reb].trim();
            }
          });
          rea.uuid = rea.requisitionType + rea.requisitionNo + rea.requisitionNumber;
          rea.status = stateGenerationMethod(rea);
        });
        base.tabelList = steam;
        base.pagination.total = res.data.total;
        defaultValueWriteBack();
      }
    });
  };

  const handlePageChange = (page: number) => {
    base.pagination.current = page;
    init();
  };

  const handlePageSizeChange = (pageSize: number) => {
    base.pagination.pageSize = pageSize;
    init();
  };

  const selectChange = (param) => {
    base.getOmnList = [];
    param.forEach((res: any) => {
      base.getOmnList.push(base.tabelList[res]);
    });
  };

  const purchaseOrderGeneration = (): any => {
    const steam = localStorage.getItem('BLISOK');
    let steamDom: any = null;
    if (!isNullPm(steam)) {
      steamDom = JSON.parse(localStorage.getItem('BLISOK') as any);
    }
    if (isNullPm(steamDom)) {
      notification.info('没有选择任何请购信息,请先选择请购信息~');
      return false;
    }
    let steamOpp = null;
    steamDom.map((res: any) => {
      if (res.getOmnList.length > 0) steamOpp = res.getOmnList.length;
    });
    if (isNullPm(steamOpp)) {
      notification.info('没有选择任何请购信息,请先选择请购信息~');
      return false;
    }
    router.push({
      path: '/purchaseOrderAdd',
      query: {
        featureData: JSON.stringify(base.featureData),
      },
    });
  };

  /**
   * @exports selectAllChangeEvent  列表全选or全不选
   * @param param
   */
  const selectAllChangeEvent = () => {
    base.getOmnList = statusScreening(base.tableRef.getCheckboxRecords());

    dataProcessing();
  };

  /**
   * @exports selectChangeEvent 列表单选or多选
   * @param param
   */
  const selectChangeEvent = () => {
    base.getOmnList = statusScreening(base.tableRef.getCheckboxRecords());
    dataProcessing();
  };

  /**
   * @exports dataProcessing 数据处理,默认规定,如果只换分页，则不重置数据，如果换了条数，则重置数据
   */
  const dataProcessing = () => {
    const steam: any = localStorage.getItem('BLISOK');
    if (isNullPm(steam)) {
      const steamDom: any = [
        {
          current: base.pagination.current,
          pageSize: base.pagination.pageSize,
          getOmnList: base.getOmnList,
        },
      ];
      localStorage.setItem('BLISOK', JSON.stringify(steamDom));
    } else {
      let steamDom = JSON.parse(steam);
      let subscript = false;
      let identifier = false;
      let numberInd = 0;
      steamDom.map((res: any, index: any) => {
        if (res.pageSize != base.pagination.pageSize) {
          subscript = true;
        }
        if (res.current == base.pagination.current) {
          identifier = true;
          numberInd = index;
        }
      });
      if (subscript) {
        steamDom = [];
        steamDom.push({
          current: base.pagination.current,
          pageSize: base.pagination.pageSize,
          getOmnList: base.getOmnList,
        });
      } else {
        if (!identifier)
          steamDom.push({
            current: base.pagination.current,
            pageSize: base.pagination.pageSize,
            getOmnList: base.getOmnList,
          });
        else steamDom[numberInd].getOmnList = base.getOmnList;
      }
      localStorage.setItem('BLISOK', JSON.stringify(steamDom));
    }
  };

  /**
   * @exports statusScreening 将已完成的数据筛选掉
   */
  const statusScreening = (param) => {
    const steam: any = [];
    param.map((res: any) => {
      if (res.status != '已完成') {
        steam.push(res);
      }
    });

    return steam;
  };

  // watch(() => base.pagination, () => {
  //     init()
  // }, {
  //     deep: true
  // })

  /**
   * @exports menuConfig 表单配置器
   */
  const menuConfig = reactive<any>({
    className: 'my-menus',
    body: {
      options: [
        [{ code: 'copy', name: '复制', prefixIcon: 'vxe-icon-copy', className: 'my-copy-item' }],
        [{ code: 'viewDetails', name: '查看详情', prefixIcon: 'vxe-icon-success-circle-fill', className: 'my-copy-item' }],
      ],
    },
  });
  /**
   * @exports contextMenuBodyClickEvent 表单操作格式
   * @param param0
   */
  const contextMenuBodyClickEvent = ({ menu, row, column }) => {
    switch (menu.code) {
      case 'viewDetails':
        purchaseRequisitionDetails(row);
        break;
      case 'copy':
        // 示例
        if (row && column) {
          console.log(row, column);
          if (XEClipboard.copy(row[column.field])) {
            VXETable.modal.message({ content: '已复制到剪贴板！', status: 'success' });
          }
        }
        break;
      default:
        console.log(`点击了 ${menu.name} 选项`, row, column, row[column.field]);
    }
  };

  /**
   * @exports stateGenerationMethod 状态生成工具
   */
  const stateGenerationMethod = (param) => {
    const bindTime = formatDate(new Date(), 'yyyy-MM-dd');
    if (param.number <= param.purchasedQuantity) return '已完成';
    else if (spaceTime(bindTime, EFTimeFormatConversion(param.requirementDate)) < 0) return '异常订单';
    else if (spaceTime(bindTime, EFTimeFormatConversion(param.requirementDate)) < 7) return '临近日期';
    else if (param.purchasedQuantity > 0 && param.number > param.purchasedQuantity) return '待处理完成';
    else return '待处理';
  };

  /**
   * @exports purchaseRequisitionDetails 请购单详情
   */
  const purchaseRequisitionDetails = (param) => {
    const steam = {
      tb001: param.requisitionType,
      tb002: param.requisitionNo,
      tb003: param.requisitionNumber,
    };
    purtbSelectPurtb(steam).then((res: any) => {
      if (res.code == '200') {
        base.desData = PURTBCHANGE(res.data);
        base.visible = true;
      }
    });
  };

  /**
   * @exports resetSelectItem 重置选择项目
   */
  const resetSelectItem = () => {
    localStorage.removeItem('BLISOK');
    init();
  };

  /**
   * @exports reset 重置操作
   */
  const reset = () => {
    base.checkFrom = {
      requisitionType: null,
      requisitionNo: null,
      time: null,
      productName: null,
      articleNumber: null,
      requirementDate: null,
    };
    init();
  };

  /**
   * @exports sectionOption 部门下拉
   */
  const sectionOption = () => {
    cmsmeCmsmeVoList().then((res: any) => {
      const steam = {
        departmentName: '全部数据',
        departmentNumber: '',
      };
      if (res.code == 200) {
        base.section = res.data;
        base.section.unshift(steam);
      }
    });
  };
  return {
    handlePageChange,
    handlePageSizeChange,
    base,
    init,
    selectChange,
    purchaseOrderGeneration,
    selectAllChangeEvent,
    selectChangeEvent,
    menuConfig,
    contextMenuBodyClickEvent,
    stateGenerationMethod,
    resetSelectItem,
    reset,
  };
}
